<?php
/**
 * 鸡汤，名言等
 * 依赖于Sentence数据表
 */

namespace App\Helpers\libs;


use App\Models\Sentence;
use Illuminate\Support\Facades\Http;

class Saying
{
    /**
     * 获取毒鸡汤
     * @return string
     */
    public function getDu()
    {
        $url = 'https://du.shadiao.app/api.php';
        for ($i = 0; $i < 5; $i++) {
            $rsp = Http::get($url);
            if (strpos($rsp, '访问太') === false) {
                $s = Sentence::where('content', $rsp)->first();
                if (empty($s)) {
                    $s = new Sentence();
                    $s['content'] = $rsp;
                    $s->save();
                }
            } else {
                return 'error';
            }
        }
        return 'success';
    }

    /**
     * 判断数据库是否已经存在
     * @param $content
     * @return int
     */
    public function check($content)
    {
        // 检测是否有重复项
        $items = Sentence::all();
        $results = [];
        foreach ($items as $item) {
            $flag = true;
            foreach ($results as $result) {
                if ($result['content'] == $item['content']) {
                    $flag = false;
                    break;
                }
            }
            if ($flag) {
                $results []= $item;
            }
        }
        return count($results);
    }
}
